/// 参与者审核响应模型
/// 对应接口: POST /activities/participants/review/
class ParticipantReviewResponse {
  /// 响应状态
  final String status;
  
  /// 响应消息
  final String message;
  
  /// 活动ID
  final int? activityId;
  
  /// 用户ID
  final int? userId;
  
  /// 审核结果状态
  final String? reviewStatus;
  
  /// 审核时间
  final String? reviewTime;
  
  /// 额外数据
  final Map<String, dynamic>? extraData;

  ParticipantReviewResponse({
    required this.status,
    required this.message,
    this.activityId,
    this.userId,
    this.reviewStatus,
    this.reviewTime,
    this.extraData,
  });

  /// 是否成功
  bool get isSuccess => status == 'success';

  /// 是否审核通过
  bool get isApproved => reviewStatus == 'approved';

  /// 是否审核拒绝
  bool get isRejected => reviewStatus == 'rejected';

  /// 从JSON创建实例
  factory ParticipantReviewResponse.fromJson(Map<String, dynamic> json) {
    return ParticipantReviewResponse(
      status: json['status'] ?? 'error',
      message: json['message'] ?? '审核操作失败',
      activityId: json['activity_id'] is String 
          ? int.tryParse(json['activity_id'])
          : json['activity_id'],
      userId: json['user_id'] is String 
          ? int.tryParse(json['user_id'])
          : json['user_id'],
      reviewStatus: json['review_status'],
      reviewTime: json['review_time'],
      extraData: json['extra_data'],
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'message': message,
      if (activityId != null) 'activity_id': activityId,
      if (userId != null) 'user_id': userId,
      if (reviewStatus != null) 'review_status': reviewStatus,
      if (reviewTime != null) 'review_time': reviewTime,
      if (extraData != null) 'extra_data': extraData,
    };
  }

  @override
  String toString() {
    return 'ParticipantReviewResponse{status: $status, message: $message, activityId: $activityId, userId: $userId, reviewStatus: $reviewStatus}';
  }
}

/// 发布者活动参与者数据模型
/// 对应 /publisher/activity/participants/ 接口返回的数据
class PublisherParticipantsData {
  /// 用户ID
  final int userId;
  
  /// 用户昵称
  final String userName;
  
  /// 用户年龄
  final int? userAge;
  
  /// 用户性别
  final String? userGender;
  
  /// 用户头像URL
  final String? userAvatarUrl;
  
  /// 用户签名
  final String? userSignature;
  
  /// 活动ID
  final int activityId;
  
  /// 活动名称
  final String activityName;
  
  /// 申请时间
  final String applicationTime;
  
  /// 参与者状态：pending（待审核）、approved（已通过）、rejected（已拒绝）
  final String participantStatus;
  
  /// 用户等级（实际存储的是积分）
  final int? userLevel;
  
  /// 🔥 新增：用户生日
  final String? userBirthday;
  
  /// 额外数据
  final Map<String, dynamic>? extraData;

  PublisherParticipantsData({
    required this.userId,
    required this.userName,
    this.userAge,
    this.userGender,
    this.userAvatarUrl,
    this.userSignature,
    required this.activityId,
    required this.activityName,
    required this.applicationTime,
    required this.participantStatus,
    this.userLevel,
    this.userBirthday,
    this.extraData,
  });

  /// 是否待审核
  bool get isPending => participantStatus == 'pending' || participantStatus == '待审核';
  
  /// 是否已通过
  bool get isApproved => participantStatus == 'approved' || participantStatus == '已通过';
  
  /// 是否已拒绝
  bool get isRejected => participantStatus == 'rejected' || participantStatus == '已拒绝';

  /// 从JSON创建实例
  factory PublisherParticipantsData.fromJson(Map<String, dynamic> json) {
    // 🎯 根据MyApplication2项目和实际响应数据，字段使用驼峰命名法
    
    // 🔄 状态映射：根据reviewStatus和isApproved字段确定参与者状态
    String status = 'pending'; // 默认状态
    final reviewStatus = json['reviewStatus'] as String?;
    final isApproved = json['isApproved'] as bool?;
    
    if (reviewStatus == '审核中' || reviewStatus == 'pending') {
      status = 'pending';
    } else if (isApproved == true || reviewStatus == '已通过' || reviewStatus == 'approved' || reviewStatus == '通过') {
      status = 'approved';
    } else if (isApproved == false || reviewStatus == '已拒绝' || reviewStatus == 'rejected' || reviewStatus == '未通过' || reviewStatus == '拒绝') {
      // 🔥 修复：添加"未通过"状态的映射
      status = 'rejected';
    }
    
    return PublisherParticipantsData(
      userId: json['userId'] is String ? int.parse(json['userId']) : (json['userId'] as int),
      userName: json['username'] ?? '未知用户',
      userAge: json['userAge'] as int?,
      userGender: json['userGender'] as String?,
      userAvatarUrl: json['userAvatar'] as String?, // 注意字段名是userAvatar而不是userAvatarUrl
      userSignature: json['userSignature'] as String?,
      activityId: json['activityId'] is String ? int.parse(json['activityId']) : (json['activityId'] as int),
      activityName: json['activityTitle'] ?? '未知活动',
      applicationTime: json['joinTime'] ?? '',
      participantStatus: status, // 使用计算出的状态
      userLevel: json['userPoints'] as int?, // 使用userPoints作为等级
      userBirthday: json['userBirthday'] as String?, // 🔥 新增：用户生日
      extraData: json['userExtraData'] as Map<String, dynamic>?, // 对应userExtraData字段
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'user_id': userId,
      'user_name': userName,
      if (userAge != null) 'user_age': userAge,
      if (userGender != null) 'user_gender': userGender,
      if (userAvatarUrl != null) 'user_avatar_url': userAvatarUrl,
      if (userSignature != null) 'user_signature': userSignature,
      'activity_id': activityId,
      'activity_name': activityName,
      'application_time': applicationTime,
      'participant_status': participantStatus,
      if (userLevel != null) 'user_level': userLevel,
      if (userBirthday != null) 'user_birthday': userBirthday,
      if (extraData != null) 'extra_data': extraData,
    };
  }

  @override
  String toString() {
    return 'PublisherParticipantsData{userId: $userId, userName: $userName, activityName: $activityName, participantStatus: $participantStatus}';
  }
}

/// 发布者活动参与者响应模型
class PublisherParticipantsResponse {
  /// 响应状态
  final String status;
  
  /// 响应消息
  final String message;
  
  /// 参与者数据列表
  final List<PublisherParticipantsData> participants;
  
  /// 总数
  final int total;
  
  /// 发布者ID
  final int? publisherId;

  PublisherParticipantsResponse({
    required this.status,
    required this.message,
    required this.participants,
    required this.total,
    this.publisherId,
  });

  /// 是否成功
  bool get isSuccess => status == 'success';
  
  /// 待审核的参与者
  List<PublisherParticipantsData> get pendingParticipants => 
      participants.where((p) => p.isPending).toList();
  
  /// 已通过的参与者
  List<PublisherParticipantsData> get approvedParticipants => 
      participants.where((p) => p.isApproved).toList();
  
  /// 已拒绝的参与者
  List<PublisherParticipantsData> get rejectedParticipants => 
      participants.where((p) => p.isRejected).toList();

  /// 从JSON创建实例
  factory PublisherParticipantsResponse.fromJson(Map<String, dynamic> json) {
    // 服务器返回的数据结构：{status, data: {total, activities, participants, pagination}}
    final dataMap = json['data'] as Map<String, dynamic>? ?? {};
    final participantsList = dataMap['participants'] as List? ?? [];
    final totalCount = dataMap['total'] as int? ?? 0;
    
    return PublisherParticipantsResponse(
      status: json['status'] ?? 'error',
      message: json['message'] ?? '查询失败',
      participants: participantsList
          .map((item) => PublisherParticipantsData.fromJson(item as Map<String, dynamic>))
          .toList(),
      total: totalCount,
      publisherId: json['publisher_id'] is String 
          ? int.tryParse(json['publisher_id'])
          : json['publisher_id'],
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'message': message,
      'data': participants.map((p) => p.toJson()).toList(),
      'total': total,
      if (publisherId != null) 'publisher_id': publisherId,
    };
  }

  @override
  String toString() {
    return 'PublisherParticipantsResponse{status: $status, total: $total, participants: ${participants.length}}';
  }
}
